﻿namespace TanzimSaqib.NoBrainer.Sample.Controllers
{
    using System.Web.Security;
    using DataAccess;

    public interface IAccountController
    {
        AccountModel Login(AccountModel user);
    }

    public class AccountController : ControllerBase, IAccountController
    {
        public AccountModel Login(AccountModel user)
        {
            /* 
                Example: how Models can be validated and 
                error messages can be sent from Controllers.
            */

            // Example: how error messages can be set from the Controllers 
            if (string.IsNullOrEmpty(user.UserName))
                user.ErrorMessages["UserName"] = "UserName cannot be empty.";

            // Example: how to enable/disable CMS based error messages to the UI
            if (string.IsNullOrEmpty(user.Password))
                user.CmsErrorMessages["Password"] = true;

            if(string.IsNullOrEmpty(user.UserName) || string.IsNullOrEmpty(user.Password))
            {
                user.ErrorMessage = "There are errors. Please fix them and try again.";                
            }
            else
            {
                if (!Membership.ValidateUser(user.UserName, user.Password))
                {
                    user.ErrorMessage = "UserName/Password combination is incorrect.";
                }
                else
                {
                    FormsAuthentication.SetAuthCookie(user.UserName, user.PersistentCookieEnabled);
                    user.IsValid = true;
                }
            }

            return user;
        }
    }
}
    